<?php
	session_start();
?>
<html>
<head>
	<title> SocialFilter - keep up with all your status updates easily!</title>
	<script type="text/javascript" src="./../jquery/jquery-1.4.3.min.js"></script>
	<script type="text/javascript" src="./javascript/feed_reader.js"></script>
	<script type="text/javascript" src="./javascript/main.js"></script>
	<LINK href="css/styles.css" rel="stylesheet" type="text/css">
</head>
<body>


<?php
require_once('twitteroauth/twitteroauth.php');
require_once("db_functions.php");
require_once("config.php");
require_once("facebook.php");

$twitterAccountName = null;
$twitterSiteName = null;
$twitterToken = null;

$twitterContent = '';
/* If access tokens are not available redirect to connect page. */
if (empty($_SESSION['access_token']) || empty($_SESSION['access_token']['oauth_token']) || empty($_SESSION['access_token']['oauth_token_secret'])) {
	$twitterContent = '<a href="./redirect.php"><img src="./images/lighter.png" alt="Sign in with Twitter"/></a>';
	$logged_into_twitter = false; 
}
/* Get user access tokens out of the session. */
else
{
	$access_token = $_SESSION['access_token'];
	$logged_into_twitter = true;
	/* Create a TwitterOauth object with consumer/user tokens. */
	$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, $access_token['oauth_token'], $access_token['oauth_token_secret']);

	/* If method is set change API call made. Test is called by default. */
	//$content = $connection->get('account/verify_credentials');
	//$content = $connection->get('statuses/friends');
	$twitterAccountName = $access_token["screen_name"];
	$twitterSiteName = "twitter";
	$twitterToken = $access_token["oauth_token"]." ".$access_token["oauth_token_secret"];
	$twitterContent = '';
}
echo $twitterContent;

// Create our Application instance.
$facebook = new Facebook(array(
  'appId'  => $app_id,
  'secret' => $secret,
  'cookie' => true,
));

// We may or may not have this data based on a $_GET or $_COOKIE based session.
//
// If we get a session here, it means we found a correctly signed session using
// the Application Secret only Facebook and the Application know. We dont know
// if it is still valid until we make an API call using the session. A session
// can become invalid if it has already expired (should not be getting the
// session back in this case) or if the user logged out of Facebook.
$session = $facebook->getSession();
$userId = null; 
$me = null;

// Session based API call.
if ($session) {
  try {
    $uid = $facebook->getUser();
    $me = $facebook->api('/me');
  } catch (FacebookApiException $e) {
	error_log($e);
  }
} 
	
 
// if logged into facebook, set logged_in to true and content to button HTML. else, false and ''. 
if ($me) {
	$logged_into_facebook = true; 
	$facebook_content = ''; 
} else {
	$logged_into_facebook = false;	
	$facebook_content = '<a href="https://graph.facebook.com/oauth/authorize?client_id=169651206390011&redirect_uri=http://'.$ip_address.'/SocialFilter%20www/index.php&type=user_agent&scope=offline_access,read_stream"><img src="http://static.ak.fbcdn.net/rsrc.php/zB6N8/hash/4li2k73z.gif" style="float:right"></a>';
}

echo $facebook_content; 

$facebook_token = $session['access_token']; 
$facebook_name = $me['name']; 
		
		
//
if($logged_into_facebook && $logged_into_twitter){
	
	//Our site's IDs associated with the respective account
	$twitid = GetUserId($twitterAccountName, $twitterSiteName, $twitterToken);
	$faceid = GetUserId($facebook_name, "facebook", $facebook_token);
		
	if($twitid == null && $faceid == null) {
		AddNewUser($twitterAccountName, $twitterSiteName, $twitterToken, $twitid);
		AddAccount($twitid, $facebook_name, "facebook", $facebook_token);
		$userId = $twitid; 
	} else if ($twitid == null && $logged_into_twitter) { 
		AddAccount($faceid, $twitterAccountName, $twitterSiteName, $twitterToken);
		$userId = $faceid; 
	} else if ($faceid == null && logged_into_facebook) {
		AddAccount($twitid, $facebook_name, "facebook", $facebook_token);
		$userId = $twitid; 
	} else if ($twitid != $faceid) {
		MergeUsers($twitid, $faceid);
		$userId = $twitid; 
	} else if ($twitid == $faceid) {
		$userId = $twitid; 
	} else {
		echo 'Something bad happened'; 
	}
} else if ($logged_into_facebook) {
	
	//Our site's IDs associated with the respective account
	$faceid = GetUserId($facebook_name, "facebook", $facebook_token);
		
	if ($faceid == null) {
		echo "<br>Adding new user";
		$faceid = AddNewUser($facebook_name, "facebook", $facebook_token, $faceid);
		echo "<br>faceid: ".$faceid;
	} 
	
	$userId = $faceid; 
} else if ($logged_into_twitter) { 
	
	//Our site's IDs associated with the respective account
	$twitid = GetUserId($twitterAccountName, $twitterSiteName, $twitterToken);
		
	if ($twitid == null) {
		$twitid = AddNewUser($twitterAccountName, $twitterSiteName, $twitterToken, $twitid);
	} 
	
	$userId = $twitid; 	
} 

?>

<!-- Facebook script stuff. This is necessary for log-in to work correctly--> 
<div id="fb-root"></div>
<script>
  window.fbAsyncInit = function() {
	FB.init({
	  appId   : '<?php echo $facebook->getAppId(); ?>',
	  session : <?php echo json_encode($session); ?>, // don't refetch the session when PHP already has it
	  status  : true, // check login status
	  cookie  : true, // enable cookies to allow the server to access the session
	  xfbml   : true // parse XFBML
	});

	// whenever the user logs in, we refresh the page
	FB.Event.subscribe('auth.login', function() {
	  window.location.reload();
	});
  };

  (function() {
	var e = document.createElement('script');
	e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
	e.async = true;
	document.getElementById('fb-root').appendChild(e);
  }());
</script>
<!--End of Facebook login script--> 

<script type="text/javascript">
	var userId = <?php echo $userId; ?>;
</script>

<div class="icon">
	<img src="images/Logo.png" alt="Logo">
</div>
<div class="outerLeft">My Feeds<br/>
	<div id="feeds">
		
		<?php
		
			// display a list of feeds
			// $userId = 1;
			$feeds = GetFeeds($userId);
	
			if($feeds != null)
			{
				foreach( $feeds as $feed )
				{
					echo "<div id='feed-".$feed["feedid"]."' ><a class='clickable' onclick='requestFeed(\"".$feedsDirectory.$feed["url"]."\"); requestFilters(\"".$feed["feedid"]."\"); currentFeedId=".$feed["feedid"]."'>".$feed["name"]."</a> <a class=\"link\" onclick='deleteFeed(\"".$feed["feedid"]."\")'>Delete</a></div>";
				}
			}
		?>
	</div>
	<button type="button" onClick="addFeed(<?php echo($userId); ?>)">Add Feed</button><input id="feedString" type="text" /><br />
</div>

<div class="outerRight">Feed Filters<br/>
	<div id="filters">
	</div>
<button type="button" onClick="addFilter()">Add Filter</button><input id="filterString" type="text" /><br />
</div>

<div class="newsfeed" style="float:center">News Feed<br/>
	<div id="url">RSS URL:</div>
	<div class="newsbox" id="items">
	</div>
</div>

<br/>
<script type="text/javascript">
</script>
</body>
</html>